<?php

namespace app\common\business\log;

use \think\Session;
use app\common\mysql\Users as newsMysql;

class SmsIp extends \app\common\business\AbstractModel {

    /**
     * 校验，写入日志
     * type  1 => "注册", 2 => "绑定",3 => "忘记密码"
     *
     * @param type $type
     */
    public static function validate($params) {
        $type = $params['register'];
        $mobile = $params['mobile'];
        $code = $params['code'];
        $ip = self::getClientIp();
        $longIp = ip2long($ip);
        if ($longIp == -1 || $longIp === FALSE) {
            exception("系统拥堵，请稍候再试", 100001);
        }
        $data = array(
            'log_type' => $type,
            'ip' => $longIp,
            'request_ip' => $ip,
            'request_uri' => (empty($_SERVER['REQUEST_URI']) ? '' : $_SERVER['REQUEST_URI']),
            'add_time' => time(),
            'mobile' => $mobile,
        );

        if (self::validateIp($type, $longIp, $mobile)) {
            $data['status'] = 1;
            return self::insertSmsLog($data, $code);
        } else {
            $data['status'] = 2;
            self::insertSmsLog($data, $code);
            exception("系统拥堵，请稍候再试", 100001);
        }
    }

    /**
     * 校验IP
     *
     * @param type $type
     * @param type $ip
     * @param type $maxNum
     * @return boolean
     */
    protected static function validateIp($type, $ip, $mobile, $maxNum = 10) {

        $where = array(
            'log_type' => $type,
            'ip' => $ip,
            'mobile' => $mobile,
        );
        $totalNum = self::getIptotal($where);
        $totalNum = $totalNum ? $totalNum[0]['total'] : 0;
        if ($maxNum > $totalNum) {
            return true;
        } else {
            return false;
        }
    }

    /**
     * 获取ip一天请求短信次数
     */
    public static function getIptotal($params) {
        return newsMysql::name('user_log_sms_ip')
                        ->field('count(0) as total')
                        ->where($params)
                        ->whereTime('add_time', 'today')
                        ->select();
    }

    /*
     * 记录短信的信息
     *
     * */

    public static function insertSmsLog($params, $code) {
        newsMysql::startTrans();

        if (newsMysql::name('user_log_sms_ip')
                        ->insert($params)) {
            if ($params['status'] == 1) {
                $post['code_type'] = $params['log_type'];
                $post['mobile'] = $params['mobile'];
                $post['code'] = $code;
                $post['add_time'] = time();
                if (!self::codeLoge($post))
                    newsMysql::rollback();
            }
        }
        newsMysql::commit();
        return true;
    }

    /*
     * 记录发送短信的信息
     *
     * */

    public static function codeLoge($params) {
        return newsMysql::name('user_code')
                        ->insert($params);
    }

}
